package com.brickworkers.codemaker.service;


import static com.brickworkers.codemaker.utils.MakerconfResource.rb;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.brickworkers.codemaker.domain.Row;
import com.brickworkers.codemaker.domain.Row.Type;
import com.brickworkers.codemaker.domain.Table;

public class TableMessageService {
	
	Connection conn = SqlConnectionFactory.getConnection();
	
	
	public List<Table> getTables(){
		List<Table> tableList = new ArrayList<Table>();
		
		try {
			DatabaseMetaData databaseMetaData = conn.getMetaData();
		
		//如果是要生成数据库
		if(Boolean.valueOf(rb.getString("isAllDatabase"))){
			//获取所有表名
			ResultSet rs = databaseMetaData.getTables(null, null, null, null);
			List<String> tables = new ArrayList<String>();
			while(rs.next()){
				tables.add(rs.getString(3));
			}
			
			//获取table
			for (String tableName : tables) {
				tableList.add(getTable(tableName));
			}
			
		}else{
			tableList.add(getTable(rb.getString("table")));
		}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return tableList;
	}
	
	public static void main(String[] args) {
		TableMessageService messageService = new TableMessageService();
		messageService.getTables();
	}
	
	//获取表的信息
	public Table getTable(String tableName){
		Table table = new Table(tableName);
		try {
			
			DatabaseMetaData databaseMetaData = conn.getMetaData();
			//获取列信息
			ResultSet rs = databaseMetaData.getColumns(null, null, tableName, null);
			List<Row> rows = new ArrayList<Row>(); 
			while(rs.next()){
				Row row = new Row.Builder(rs.getString(4), Type.getType(rs.getInt(5))).description(rs.getString(12)).build();
				rows.add(row);
			}
			table.setRows(rows);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(table);
		return table;
	}
	
	
}
